package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfigImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class PayHelper {

    private WXPay wxPay;
    private WXPayConfigImpl payConfig;

    public PayHelper(WXPay wxPay, WXPayConfigImpl payConfig) {
        this.wxPay = wxPay;
        this.payConfig = payConfig;
    }

    public String getPayUrl(String desc, Long orderId, Long totalFee) {
        // 请求参数：
        Map<String, String> data = new HashMap<String, String>();
        // 商品描述
        data.put("body", desc);
        // 订单编号
        data.put("out_trade_no", orderId.toString());
        // 支付金额
        data.put("total_fee", totalFee.toString());
        // 终端IP
        data.put("spbill_create_ip", "123.12.12.123");
        // 交易类型：NATIVE代表扫码支付
        data.put("trade_type", payConfig.getTradeType());  // 此处指定为扫码支付

        try {
            // 统一下单
            Map<String, String> resp = wxPay.unifiedOrder(data);

/*            // 通信校验
            checkReturnCode(resp);
            // 业务校验
            checkResultCode(resp);
            checkResultCode(resp);
            // 签名校验
            checkSignature(resp);
*/
            String codeUrl = resp.get("code_url");
            if (StringUtils.isBlank(codeUrl)) {
                // 链接不存在
                throw new RuntimeException("统一下单失败");
            }
            return codeUrl;
        } catch (Exception e) {
            log.error("下单失败！", e);
            throw new RuntimeException(e);
        }
    }

    public void checkSignature(Map<String, String> resp) {
        boolean boo = false;
        try {
            boo = wxPay.isResponseSignatureValid(resp);
        } catch (Exception e) {
            throw new RuntimeException("签名校验异常！");
        }
        if(!boo){
            // 签名有误
            throw new RuntimeException("签名有误");
        }
    }

    public void checkResultCode(Map<String, String> resp) {
        String resultCode = resp.get("result_code");
        if("FAIL".equals(resultCode)){
            // 业务失败，抛异常
            throw new RuntimeException("业务失败，" + resp.get("err_code_des"));
        }
    }

    public void checkReturnCode(Map<String, String> resp) {
        String returnCode = resp.get("return_code");
        if("FAIL".equals(returnCode)){
            // 通信失败，抛异常
            throw new RuntimeException("通信失败，" + resp.get("return_msg"));
        }
    }
}
